package com.school.edupoint.service;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.edupoint.config.EduContext;
import com.school.edupoint.mapper.GiftMapper;
import com.school.edupoint.mapper.StudentGiftMapper;
import com.school.edupoint.mapper.StudentMapper;
import com.school.edupoint.model.Gift;
import com.school.edupoint.model.Student;
import com.school.edupoint.model.StudentGift;
import com.school.edupoint.template.OssTemplate;
import com.school.edupoint.vo.StudentVO;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Service
public class StudentService {
    @Autowired
    private EduContext eduContext;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private GiftMapper giftMapper;
    @Autowired
    private StudentGiftMapper studentGiftMapper;
    @Autowired
    private OssTemplate ossTemplate;

    public Student login(String username, String password) {
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getUsername, username);
        Student user = studentMapper.selectOne(queryWrapper);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    public Student getInfo(Integer id) {
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getId, id);
        return studentMapper.selectOne(queryWrapper);
    }

    public IPage<Student> selectPage(String username, int pageNum, int pageSize) {
        Page<Student> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        if (username == null || username.trim().isEmpty()) {

        } else {
            wrapper.like(Student::getNickname, username);
        }

        wrapper.orderByDesc(Student::getPoint);
        return studentMapper.selectPage(page, wrapper);
    }

    /**
     * 新增或更新
     *
     * @param studentVO 实体
     * @return 提示
     */
    public StudentVO save(StudentVO studentVO) {
        if (studentVO.getId() == null) {
            studentVO.setCreateBy(eduContext.getUser().getId());
            studentVO.setCreateTime(new Date());
            if (studentVO.getNickname() == null && studentVO.getNickname().isEmpty()) {
                studentVO.setNickname("这个用户很神秘，没写昵称");
            }
            studentVO.setPoint(0);
            studentMapper.insert(studentVO);
        } else {
            String oldPoster = studentVO.getOldPoster();
            if (oldPoster != null && !oldPoster.isEmpty()) {
                ossTemplate.asyncDeleteByUrl(oldPoster); // 异步删除
            }
            Integer userID = eduContext.getUser().getId();
            studentVO.setUpdateBy(userID);
            studentVO.setUpdateTime(new Date());
            studentMapper.updateById(studentVO);
        }

        return studentVO;
    }

    //用户注册
    public String register(Student student) {
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();

        List<Student> students = studentMapper.selectList(queryWrapper);
        for (Student s : students) {
            if (s.getUsername().equals(student.getUsername())) {
                return "该用户名已被使用";
            }
        }
        if (student.getId() == null) {
            student.setCreateBy(1);
            student.setCreateTime(new Date());
            if (student.getNickname() == null && student.getNickname().isEmpty()) {
                student.setNickname("这个用户很神秘，没写昵称");
            }
            student.setPoint(0);
            studentMapper.insert(student);
        }
        return "注册成功";
    }


    public void delete(Integer id) {
        studentMapper.deleteById(id);
    }

    public void updatePonint(Integer studentId, Integer activityPoint) {
        studentMapper.updatePonint(studentId, activityPoint);
    }

    /**
     * 兑换礼物
     *
     * @param giftId
     * @param studentId
     * @return
     */
    public String cash(Integer giftId, Integer studentId, String receiveName, String receivePhone, String address) {
//        根据学生ID查询学生信息
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getId, studentId);
        Student student = studentMapper.selectOne(queryWrapper);
        //根据活动ID查询活动信息
        LambdaQueryWrapper<Gift> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Gift::getId, giftId);
        Gift gift = giftMapper.selectOne(queryWrapper1);
        int kucun = gift.getHeadCount() - gift.getReg();
        if (kucun > 0) {
            if (student.getPoint() >= gift.getPoint()) {
                //1、学生减积分
                int newPoint = student.getPoint() - gift.getPoint();
                student.setPoint(newPoint);
                student.setId(studentId);
                studentMapper.updateById(student);
                //2、礼物减库存
                gift.setReg(gift.getReg() + 1);
                gift.setId(giftId);
                giftMapper.updateById(gift);
                //3、存兑换记录
                StudentGift studentGift = new StudentGift();
                studentGift.setStudentId(studentId);
                studentGift.setStudentName(student.getNickname());
                studentGift.setGiftId(giftId);
                studentGift.setGiftName(gift.getName());
                studentGift.setImageUrl(gift.getImageUrl());
                studentGift.setPoint(gift.getPoint());
                //兑换状态1已兑换未发货，2已发货,3已送达，4取消）
                studentGift.setStatus(1);
                studentGift.setReceivePhone(receivePhone);
                studentGift.setReceiveName(receiveName);
                studentGift.setAddress(address);
                studentGift.setCreateTime(new Date());
                studentGift.setCreateBy(eduContext.getStudent().getId());
                studentGiftMapper.insert(studentGift);
            } else {
                return "积分不足";
            }
        } else {
            return "已无库存";
        }

        return "兑换成功";
    }


    /**
     * 上传图片
     *
     * @param photo
     * @return
     */
    public String uploadPhoto(MultipartFile photo) throws Exception {
        //将图片上传到阿里云Oss

        String photoUrl = ossTemplate.upload(photo.getOriginalFilename(), photo.getInputStream());

        return photoUrl;

    }

    public Long selectAll() {
        Long count = studentMapper.selectCount(null);
        return count;
    }

    public Integer selectNewUsersWithIn24h() {

        return studentMapper.selectNewUsersWithIn24h();
    }

    public void exportStudents(HttpServletResponse response) throws IOException {
        List<Student> students = studentMapper.selectList(null);

//        设置响应的内容类型为 Excel 文件。
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //        设置响应头信息，告诉浏览器这是一个附件，文件名为 students.xlsx。
        response.setHeader("Content-disposition", "attachment;filename=students.xlsx");
//         使用EasyExcel写入数据
        //         使用EasyExcel写入数据，通过 response.getOutputStream() 输出流返回给浏览器。
//        EasyExcel.write(response.getOutputStream(), Suguan.class)：创建一个 Excel 写操作的对象，指定输出流和数据模型类。
//.sheet("Sheet1")：指定工作表的名称为 "Sheet1"。
//.doWrite(users)：将 users 列表中的数据写入到指定的工作表中。

        // 使用excludeColumnFieldNames排除不需要的字段
        Set<String> excludeFields = new HashSet<>();
        excludeFields.add("image_url");
        excludeFields.add("password");


        EasyExcel.write(response.getOutputStream(), Student.class).excludeColumnFieldNames(excludeFields).sheet("学生").doWrite(students);


    }
}
